package com.lvmama.dest.schedule.web;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lvmama.dest.schedule.moudule.ResultHandler;
import com.lvmama.dest.schedule.po.MonitorScheduleTaskType;
import com.taobao.pamirs.schedule.strategy.ManagerFactoryInfo;
import com.taobao.pamirs.schedule.strategy.ScheduleStrategy;
import com.taobao.pamirs.schedule.strategy.ScheduleStrategyRunntime;
import com.taobao.pamirs.schedule.strategy.TBScheduleManagerFactory;
import com.taobao.pamirs.schedule.taskmanager.ScheduleServer;
import com.taobao.pamirs.schedule.taskmanager.ScheduleTaskItem;
import com.taobao.pamirs.schedule.taskmanager.ScheduleTaskType;

/**
 * @Title: ScheduleAction.java
 * @Package com.lvtu.monitor.module.web.schedule
 * @Description: TODO
 * @author dengcheng
 * @date 2015-6-11 下午1:55:02
 * @version V1.0.0
 */

@Controller
@RequestMapping("/schedule")
public class ScheduleAction {

	private final static Logger logger = Logger.getLogger(ScheduleAction.class);

	@Autowired
	TBScheduleManagerFactory tBScheduleManagerFactory;

	
	
	
	@RequestMapping("/toTbSchedule")
	public String toFirstView() {
		return "schedule/index";
	}
	
	
	
	@RequestMapping("/toScheduleManager")
	public String toCount() {
		return "schedule/schedule_list";
	}

	/**
	 * @Description: 分页显示调度策略信息列表
	 * @param page
	 *            页码
	 * @param rows
	 *            每页条数
	 * @return
	 * @author xuqianmeng
	 * @date 2015年8月5日 下午6:40:33
	 */
	@RequestMapping(value="/loadScheduleStrategy", produces = "application/json; charset=utf-8")
	@ResponseBody
	public ResultHandler loadScheduleStrategy(int page, int rows) {
		ResultHandler result = new ResultHandler();
		try {
			logger.info("#############################loadScheduleStrategy start");
			List<ScheduleStrategy> list = tBScheduleManagerFactory
					.getScheduleStrategyManager().loadAllScheduleStrategy();
			Collections.sort(list ,new Comparator<ScheduleStrategy> () {
	            @Override
	            public int compare(ScheduleStrategy s1, ScheduleStrategy s2) {
	                return s1.getTaskName().compareTo(s2.getTaskName());
	            }
			});
			logger.info("#############################loadScheduleStrategy size:"+list.size());
			result.setTotal(list.size());
			result.setRows(list.subList((page - 1) * rows,
					page * rows > list.size() ? list.size() : page * rows));
		} catch (Exception e) {
			logger.error(e.getMessage());
			logger.info(e.toString());
		}
		return result;
	}

	/**
	 * @Description: 创建调度策略
	 * @param scheduleStrategy
	 *            调度策略实体
	 * @return 处理结果
	 * @author xuqianmeng
	 * @date 2015年8月5日 下午6:38:41
	 */
	@RequestMapping(value = "/createScheduleStrategy", produces = "application/json; charset=utf-8")
	@ResponseBody
	public String createScheduleStrategy(ScheduleStrategy scheduleStrategy) {
		try {
			//默认策略是关闭的
			scheduleStrategy.setSts("pause");
			tBScheduleManagerFactory.getScheduleStrategyManager()
					.createScheduleStrategy(scheduleStrategy);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return e.getMessage();
		}
		return "true";
	}

	/**
	 * @Description: 删除策略
	 * @param strategyName
	 *            策略名称
	 * @return 处理结果
	 * @author xuqianmeng
	 * @date 2015年8月5日 下午6:42:26
	 */
	@RequestMapping(value = "/delScheduleStrategy", produces = "application/json; charset=utf-8")
	@ResponseBody
	public String delScheduleStrategy(
			@RequestParam("strategyName") String strategyName) {
		try {
			tBScheduleManagerFactory.getScheduleStrategyManager()
					.deleteMachineStrategy(strategyName, true);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return e.getMessage();
		}
		return "true";
	}

	/**
	 * @Description: 编辑策略
	 * @param scheduleStrategy
	 *            调度策略实体
	 * @return 处理结果
	 * @author xuqianmeng
	 * @date 2015年8月5日 下午6:43:26
	 */
	@RequestMapping(value = "/editScheduleStrategy", produces = "application/json; charset=utf-8")
	@ResponseBody
	public String editScheduleStrategy(ScheduleStrategy scheduleStrategy) {
		try {
			//默认策略是关闭的
			scheduleStrategy.setSts("pause");
			tBScheduleManagerFactory.getScheduleStrategyManager()
					.updateScheduleStrategy(scheduleStrategy);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return e.getMessage();
		}
		return "true";
	}

	/**
	 * @Description: 更改策略的任务状态(停止/恢复)
	 * @param strategyName
	 *            策略名称
	 * @param sts
	 *            策略当前任务状态
	 * @return 处理结果
	 * @author xuqianmeng
	 * @date 2015年8月5日 下午6:44:55
	 */
	@RequestMapping(value = "/editstsScheduleStrategy", produces = "application/json; charset=utf-8")
	@ResponseBody
	public String editstsScheduleStrategy(
			@RequestParam("strategyName") String strategyName,
			@RequestParam("sts") String sts) {
		try {
			if ("pause".equals(sts)) {
				tBScheduleManagerFactory.getScheduleStrategyManager().resume(strategyName);
			} else if ("resume".equals(sts)) {
				//关闭策略
                tBScheduleManagerFactory.getScheduleStrategyManager().pause(strategyName);
                //清理任务
                ScheduleStrategy scheduleStrategy = tBScheduleManagerFactory.getScheduleStrategyManager().loadStrategy(strategyName);
                String baseTaskType = scheduleStrategy.getTaskName();
                logger.info("stop strategy:"+strategyName+",clear task:"+baseTaskType);
                tBScheduleManagerFactory.getScheduleDataManager().clearTaskType(baseTaskType);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			return e.getMessage();
		}
		return "true";
	}

	/**
	 * @Description:策略运行时的信息
	 * @param strategyName 策略名称
	 * @param uuid 机器ID
	 * @return
	 * @author xuqianmeng
	 * @date 2015年8月6日 下午4:17:56
	 */
	@RequestMapping("/loadScheduleStrategyRunntime")
	@ResponseBody
	public List<ScheduleStrategyRunntime> loadScheduleStrategyRunntime(
			String strategyName, String uuid) {
		List<ScheduleStrategyRunntime> scheduleStrategyRunntimeList = null;
		try {
			if (strategyName != null && strategyName.trim().length() > 0) {
				scheduleStrategyRunntimeList = tBScheduleManagerFactory
						.getScheduleStrategyManager()
						.loadAllScheduleStrategyRunntimeByTaskType(strategyName);
			} else if (uuid != null && uuid.trim().length() > 0) {
				scheduleStrategyRunntimeList = tBScheduleManagerFactory
						.getScheduleStrategyManager()
						.loadAllScheduleStrategyRunntimeByUUID(uuid);
			} else {
				scheduleStrategyRunntimeList = new ArrayList<ScheduleStrategyRunntime>();
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return scheduleStrategyRunntimeList;
	}

	@RequestMapping("/toManagerTask")
	public String toManagerTask() {
		return "schedule/task_list";
	}

	/**
	 * @Description: 加载所有任务信息并分页显示
	 * @param page
	 *            页码
	 * @param rows
	 *            每页数据条数
	 * @return
	 * @author xiachengliang
	 * @date 2015年8月5日 下午6:49:59
	 */
	@RequestMapping("/loadTask")
	@ResponseBody
	public ResultHandler loadTask(int page, int rows) {
		List<ScheduleTaskType> taskTypes;
		ResultHandler result = new ResultHandler();
		try {
			taskTypes = tBScheduleManagerFactory.getScheduleDataManager()
					.getAllTaskTypeBaseInfo();
			List<MonitorScheduleTaskType> monitorScheduleTaskTypeList = new ArrayList<MonitorScheduleTaskType>();
			for (ScheduleTaskType scheduleTaskType : taskTypes) {
				MonitorScheduleTaskType mstt = new MonitorScheduleTaskType();
				BeanUtils.copyProperties(mstt, scheduleTaskType);
				monitorScheduleTaskTypeList.add(mstt);
			}
			Collections.sort(monitorScheduleTaskTypeList ,new Comparator<MonitorScheduleTaskType> () {
	            @Override
	            public int compare(MonitorScheduleTaskType s1, MonitorScheduleTaskType s2) {
	                return s1.getBaseTaskType().compareTo(s2.getBaseTaskType());
	            }
			});
			result.setTotal(monitorScheduleTaskTypeList.size());
			result.setRows(monitorScheduleTaskTypeList.subList(
					(page - 1) * rows,
					page * rows > monitorScheduleTaskTypeList.size() ? monitorScheduleTaskTypeList
							.size() : page * rows));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return result;
	}

	/**
	 * @Description: 创建新任务
	 * @param scheduleTaskType
	 *            任务对象
	 * @return 处理结果
	 * @author xiachengliang
	 * @date 2015年8月5日 下午6:51:42
	 */
	@RequestMapping("/createTasktype")
	@ResponseBody
	public boolean createTasktype(ScheduleTaskType scheduleTaskType) {
		try {
			tBScheduleManagerFactory.getScheduleDataManager()
					.createBaseTaskType(scheduleTaskType);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return false;
		}
		return true;
	}

	/**
	 * @Description: 更新任务
	 * @param scheduleTaskType
	 *            任务对象
	 * @return 处理结果
	 * @author xiachengliang
	 * @date 2015年8月5日 下午6:53:51
	 */
	@RequestMapping("/updateTasktype")
	@ResponseBody
	public boolean updateTasktype(ScheduleTaskType scheduleTaskType) {
		try {
			tBScheduleManagerFactory.getScheduleDataManager()
					.updateBaseTaskType(scheduleTaskType);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return false;
		}
		return true;
	}

	/**
	 * @Description: 删除任务
	 * @param baseTaskType
	 *            任务名称
	 * @return 处理结果
	 * @author xiachengliang
	 * @date 2015年8月5日 下午6:54:15
	 */
	@RequestMapping("/deleteTasktype")
	@ResponseBody
	public boolean deleteTasktype(String baseTaskType) {
		try {
			tBScheduleManagerFactory.getScheduleDataManager().deleteTaskType(
					baseTaskType);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return false;
		}
		return true;
	}

	/**
	 * @Description: 清理任务运行信息
	 * @param baseTaskType
	 *            任务名称
	 * @return 处理结果
	 * @author xiachengliang
	 * @date 2015年8月5日 下午6:54:58
	 */
	@RequestMapping("/clearTasktype")
	@ResponseBody
	public boolean clearTasktype(String baseTaskType) {
		try {
			tBScheduleManagerFactory.getScheduleDataManager().clearTaskType(baseTaskType);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return false;
		}
		return true;
	}
	
	/** 
	* @Description: 返回任务运行期基本信息
	* @param baseTaskType 任务名称
	* @return
	* @author xiachengliang 
	* @date 2015年8月6日 下午4:56:45 
	*/
	@RequestMapping("/loadServerListInfo")
	@ResponseBody
	public ResultHandler loadServerListInfo(String baseTaskType) {
		ResultHandler result = new ResultHandler();
		List<ScheduleServer> serverList;
		try {
		 serverList = tBScheduleManagerFactory.getScheduleDataManager().selectAllValidScheduleServer(baseTaskType);
		 result.setRows(serverList);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return result;
	}

	/** 
	* @Description: 返回任务项信息
	* @param baseTaskType 任务名称
	* @return
	* @author xiachengliang 
	* @date 2015年8月6日 下午4:57:07 
	*/
	@RequestMapping("/loadTaskItemListInfo")
	@ResponseBody
	public ResultHandler loadTaskItemListInfo(String baseTaskType) {
		ResultHandler result = new ResultHandler();
		List<ScheduleTaskItem> taskItemList;
		try {
			taskItemList = tBScheduleManagerFactory.getScheduleDataManager().loadAllTaskItem(baseTaskType);
		 result.setRows(taskItemList);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return result;
	}
	
	@RequestMapping("/toMachineManager")
	public String toMachineManager() {
		return "schedule/machine_list";
	}

	/**
	 * @Description: 加载任务处理器信息并分页显示
	 * @param page
	 *            页码
	 * @param rows
	 *            每页数据条数
	 * @return
	 * @author xiachengliang
	 * @date 2015年8月5日 下午6:56:25
	 */
	@RequestMapping("/loadMachineManager")
	@ResponseBody
	public ResultHandler loadMachineManager(int page, int rows) {
		ResultHandler result = new ResultHandler();
		try {
			List<ManagerFactoryInfo> list = tBScheduleManagerFactory
					.getScheduleStrategyManager().loadAllManagerFactoryInfo();
			result.setTotal(list.size());
			result.setRows(list.subList((page - 1) * rows,
					page * rows > list.size() ? list.size() : page * rows));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return result;
	}

	/**
	 * @Description: 改变任务处理器的工作状态(停止/恢复)
	 * @param uuid
	 *            任务处理器编号
	 * @param isStart
	 *            是否是开启状态
	 * @return
	 * @author xiachengliang
	 * @date 2015年8月5日 下午6:58:19
	 */
	@RequestMapping("/updateMachineInfo")
	@ResponseBody
	public boolean updateMachineInfo(String uuid, boolean isStart) {
		try {
			if (isStart) {
				tBScheduleManagerFactory.getScheduleStrategyManager()
						.updateManagerFactoryInfo(uuid, false);
			} else {
				tBScheduleManagerFactory.getScheduleStrategyManager()
						.updateManagerFactoryInfo(uuid, true);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return true;
	}

}
